home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 December / PCWDEC07.iso / Software / Freeware / FlashGot 0.6.4 / chrome / flashgot.jar / content / flashgot / flashgotHttpServer.js < prev    next >
Encoding:
Text File  |  2007-08-29  |  5.7 KB  |  199 lines

  1. /***** BEGIN LICENSE BLOCK *****
  2.  
  3.     FlashGot - a Firefox extension for external download managers integration
  4.     Copyright (C) 2004-2006 Giorgio Maone - g.maone@informaction.com
  5.  
  6. ***** END LICENSE BLOCK *****/
  7.  
  8. /* Data Swap HTTP server */
  9.  
  10. FlashGotHttpServer=function(fgService) {
  11.   this.fgService=fgService;
  12.   this.isDown=true;
  13.   this.serverSocket=Components.classes['@mozilla.org/network/server-socket;1'
  14.     ].createInstance(Components.interfaces.nsIServerSocket);
  15.   this.serverSocket.init(-1,true,-1);
  16.   this.isDown=false;
  17.   this.serverSocket.asyncListen(this);
  18.   this.tmpDir=this.fgService.globals.tmpDir.clone();
  19.   this.tmpDir.append("httpserv");
  20.   this.logEnabled=fgService.getPref("LeechGet.httpLog",false);
  21.   this.log("Listening");
  22. }
  23.  
  24. FlashGotHttpServer.prototype={
  25.   documents: []
  26. ,
  27.   log: function(msg){
  28.     if(this.logEnabled && this.fgService.logEnabled) {
  29.       try {
  30.         if(!this.logStream) {
  31.           const logFile=this.tmpDir.clone();
  32.           logFile.append("server.log");
  33.           logFile.createUnique(0,0600);
  34.           const logStream=Components.classes["@mozilla.org/network/file-output-stream;1"
  35.             ].createInstance(Components.interfaces.nsIFileOutputStream );
  36.           logStream.init(logFile, 0x02 | 0x10, 0600, 0 );
  37.           this.logStream=logStream;
  38.         }
  39.         msg="HttpServer:"+this.serverSocket.port+" - "+msg+"\n";
  40.         this.logStream.write(msg,msg.length);
  41.         this.logStream.flush();
  42.       } catch(ex) {}
  43.     }
  44.   }
  45. ,
  46.   onSocketAccepted: function(ss,transport) {
  47.     this.log("Accepted request from "
  48.       +transport.host+":"+transport.port);
  49.      try {
  50.         new FlashGotHttpHandler(this,transport);
  51.      } catch(ex) {
  52.        this.log(ex.message);
  53.      }
  54.   }
  55. ,
  56.   onStopListening: function(ss,status) {
  57.     this.isDown=true;
  58.     if(this.logStream) {
  59.       this.log("Stopped, status "+status);
  60.     }
  61.   }
  62. ,
  63.   randomName: function(len) {
  64.     if(!len) len=8;
  65.     var name="";
  66.     for(var j=len; j-->0;) {
  67.       name+=String.fromCharCode(65+(Math.round(Math.random()*25)));
  68.     }
  69.     return name;
  70.   }
  71. ,
  72.   addDoc: function(docSource,docType) {
  73.     if(typeof(docType)=="undefined") docType="html";
  74.     var file=this.tmpDir.clone();
  75.     file.append(this.randomName()+"."+docType);
  76.     file.createUnique(0,0600);
  77.     this.fgService.writeFile(file,docSource);
  78.     const name=file.leafName;
  79.     this.documents.push(name);
  80.     return "http://localhost:"+this.serverSocket.port+"/"+name;
  81.   }
  82. ,
  83.   getDoc: function(name) {
  84.     const docs=this.documents;
  85.     for(var j=docs.length; j-->0;) {
  86.       if(docs[j]==name) break;
  87.     }
  88.     if(j<0) return null;
  89.     var file=this.tmpDir.clone();
  90.     file.append(name);
  91.     return file.exists()?this.fgService.readFile(file):null;
  92.   }
  93. ,  
  94.   shutdown: function() {
  95.     try {
  96.       this.log("Shutting down");
  97.       if(this.logStream) {
  98.         this.logStream.close();
  99.         this.logStream=null;
  100.       }
  101.       this.serverSocket.close();
  102.     } catch(ex) {}
  103.   }
  104. }
  105.  
  106. function FlashGotHttpHandler(server,transport) {
  107.   this.server=server;
  108.   this.inputBuffer="";
  109.   this.transport=transport;
  110.   this.asyncStream=transport.openInputStream(0,0,0).QueryInterface(
  111.     Components.interfaces.nsIAsyncInputStream);
  112.   this.log("Waiting for request data...");
  113.   
  114.   const nsIThread=Components.interfaces.nsIThread;
  115.   var thread=Components.classes['@mozilla.org/thread;1'].createInstance(nsIThread);
  116.   thread.init(this, 0,  nsIThread.PRIORITY_NORMAL, nsIThread.SCOPE_GLOBAL,nsIThread.STATE_JOINABLE);
  117.   this.log("Thread started");
  118. }
  119.  
  120. FlashGotHttpHandler.prototype = {
  121.   log: function(msg) {
  122.     this.server.log(this.transport.host+":"+this.transport.port+" - "+msg);
  123.   }
  124. ,
  125.   run: function() {
  126.      this.log("I'm in thread");
  127.      this.asyncStream.asyncWait(this,0,0,null);
  128.      this.log("Asyncwait issued");
  129.   }
  130. ,  
  131.   onInputStreamReady: function(asyncStream) {
  132.     const bytesCount=asyncStream.available();
  133.     this.log("Input stream ready, available bytes: "+bytesCount);
  134.     if(bytesCount) {
  135.       const inStream=Components.classes['@mozilla.org/scriptableinputstream;1'].createInstance(
  136.         Components.interfaces.nsIScriptableInputStream);
  137.       inStream.init(asyncStream);
  138.       var chunk=inStream.read(inStream.available());
  139.       this.log("Received data chunk "+chunk);
  140.       var buffer=this.inputBuffer.concat(chunk);
  141.       var eor=chunk.length==0?buffer.length:buffer.search("\r?\n\r?\n");
  142.       this.log("EOR: "+eor);
  143.       if(eor>-1) {
  144.         var request=buffer.substring(0,eor);
  145.         this.inputBuffer="";
  146.         this.handleRequest(request);
  147.         this.close();
  148.       } else {
  149.         this.inputBuffer=buffer;
  150.         this.run();
  151.       }
  152.     } else {
  153.       this.close();
  154.     }
  155.   }
  156. ,
  157.   close: function() {
  158.     this.asyncStream.close();
  159.   }
  160. ,
  161.   buildResponse: function(body,status,contentType) {
  162.     if(!contentType) contentType="text/html";
  163.     if(!status) {
  164.       status="200 OK";
  165.     } else {
  166.       body="<h1>"+status+"</h1><pre>"
  167.         +body
  168.         +"</pre><h5>FlashGot Http Server v. 0.1</h5>"
  169.     }
  170.     return "HTTP/1.1 "+status+"\r\nContent-type: "+contentType+"\r\n\r\n"+body;
  171.   }
  172. ,
  173.   handleRequest: function(request) {
  174.     var response;
  175.     var match;
  176.     this.log("Handling request\n"+request);
  177.     try {
  178.       if(!(match=request.match(/^GET \/([^\s]*)/))) {
  179.         response=this.buildResponse(request,"400 Bad Request"); 
  180.       } else {
  181.         var doc=this.server.getDoc(match[1]);
  182.         
  183.         if(doc==null) {
  184.           response=this.buildResponse(request,"404 Not Found");
  185.         } else {
  186.           response=this.buildResponse(doc);
  187.         }
  188.       }
  189.     } catch(ex) {
  190.       response=this.buildResponse(ex.message+"\n"+request,"500 Server error");
  191.     }
  192.     var out=this.transport.openOutputStream(1,0,0);
  193.     out.write(response,response.length);
  194.     out.close();
  195.     this.log("Sent response\n"+response);
  196.   } 
  197. }
  198.  
  199.